package com.fzc.rhinooffice.common;

import android.os.Handler;
import android.os.Message;

import com.fzc.rhinooffice.common.utils.InputStreamUtil;
import com.fzc.rhinooffice.common.utils.PreferenceUtil;
import com.fzc.rhinooffice.common.utils.StringUtil;
import com.fzc.rhinooffice.config.AppConfig;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;

import org.apache.commons.lang.StringEscapeUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class RemoteInvoke {

    /**
     * 基本的post起请求
     * @param mHandler
     * @param apiCode     url  例子：http://www.gzlxsoft.com:899/app/email/
     * @param params      参数  例子：RequestParams
     * @param respondint     响应码  例子：1   ===》msg.what = -1;
     * @param identifier  标识描述 例子：identifier=新闻 ===》msg.obj = identifier + "失败！";
     * @param cacheTime   缓存有效时间  例子：5000 就是5秒，5秒内重复的请求，只会使用缓存，不需要网络请求
     * */
    private static void post(final Handler mHandler, final String apiCode, RequestParams params,  int respondint, final String identifier,int cacheTime) {
        HttpUtils http = new HttpUtils();

        int floor = 0;
        if (apiCode.equals(AppConfig.CODE_SMS_ADD)){
            floor = respondint;
            respondint = 1;
        }

        final int respond = respondint;

        String api="";
        try {
            String paramString = (params != null ? "?" + InputStreamUtil.InputStreamTOString(params.getEntity().getContent()) : "");
            LogUtils.w(identifier + "参数:\n"+paramString.replaceFirst("\\?","").replace("&","\n"));
            api = apiCode + paramString;
            LogUtils.w(identifier + "请求:"+api);
        } catch (Exception e) {
            e.printStackTrace();
        }

        http.configSoTimeout(AppConfig.HTTP_TIMEOUT); // 设置请求超时

        final Message msg = mHandler.obtainMessage();
        final String finalApi = api;
        final int finalFloor = floor;
        //5秒钟判断
        if (judgeGetJsonByNetOrMemory(api, cacheTime)) {


            http.send(HttpRequest.HttpMethod.POST,
                    apiCode, params,
                    new RequestCallBack<String>() {



                        @Override
                        public void onFailure(HttpException error, String result) {
                            msg.what = -respond;
                            msg.obj = result;

                            if (apiCode.equals(AppConfig.CODE_SMS_ADD)){
                                msg.arg1 = finalFloor;
                            }

                            mHandler.sendMessage(msg);

                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {

                            if (responseInfo != null) {
                                //缓存
                                saveJson(responseInfo.result, System.currentTimeMillis(), finalApi);
                                JSONObject jsonObject = null;
                                LogUtils.i("------" + identifier + "----responseInfo------->>"
                                        + responseInfo.result);
                                try {
                                    jsonObject = new JSONObject(responseInfo.result);
                                    if ((jsonObject.getInt("state")) == 0) {
                                        msg.what = -respond;
                                        msg.obj = jsonObject.getString("reason");
                                    } else {
                                        msg.what = respond;
                                        msg.obj = jsonObject;
                                    }
                                } catch (JSONException e) {
                                    jsonObject = new JSONObject();
                                    e.printStackTrace();
                                } finally {

                                    if (apiCode.equals(AppConfig.CODE_SMS_ADD)){
                                        msg.arg1 = finalFloor;
                                    }

                                    mHandler.sendMessage(msg);
                                }

                            } else {
                                msg.what = -respond;
                                msg.obj = "获取"+identifier + "失败！";



                                mHandler.sendMessage(msg);
                            }

                        }
                    });
        } else {
            if (mHandler != null) {
                String json = PreferenceUtil.getString(api);

                JSONObject jsonObject = null;
                LogUtils.i("------" + identifier + "----responseInfo------->>"
                        + json);
                try {
                    jsonObject = new JSONObject(json);
                    if ((jsonObject.getInt("state")) == 0) {
                        msg.what = -respond;
                        msg.obj = jsonObject.getString("reason");
                    } else {
                        msg.what = respond;
                        msg.obj = jsonObject;
                    }
                } catch (JSONException e) {
                    jsonObject = new JSONObject();
                    e.printStackTrace();
                } finally {
                    if (apiCode.equals(AppConfig.CODE_SMS_ADD)){
                        msg.arg1 = finalFloor;
                    }
                    mHandler.sendMessage(msg);
                }
            }

        }
    }


    private static RequestParams getRequestHead(Boolean isLogin) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("appkey", AppConfig.APPKEY);
        params.addBodyParameter("appsecret", AppConfig.APPSECRET);
        params.addBodyParameter("userid", AppConfig.userid);
        if (!isLogin) {
        	if(SysApplication.user!=null){
        		params.addBodyParameter("a_sessid", SysApplication.user.a_sessid);
        	}
        }

        return params;
    }



    /**
     * 判断是使用缓存数据还是网络数据
     *
     * @param api api + 参数字典字符串
     *            判断时间是否超过5分钟，超过5分钟，覆盖新的信息
     * @return YES是网络数据
     */
    public static boolean judgeGetJsonByNetOrMemory(String api, int delayTime) {
        long currentTime = System.currentTimeMillis();
        boolean isNet = false;
        if (PreferenceUtil.contains(api)) {
            isNet = false;
            long oldTime = PreferenceUtil.getLong(api + "时间cache");

            if (currentTime - oldTime > delayTime) {
                LogUtils.i("判断是使用缓存数据还是网络数据:\n接口:" + api + "\n<当前时间:" + currentTime + "(秒)>超时(" + delayTime + ")<缓存时间:" + oldTime + ">，采用网络数据");
                isNet = true;
            } else {
                isNet = false;
                LogUtils.i("判断是使用缓存数据还是网络数据:\n接口:" + api + "\n<当前时间:" + currentTime + "(秒)>尚未超时(" + delayTime + ")<缓存时间:" + oldTime + ">，使用缓存数据");
            }
        } else {
            LogUtils.i("判断是使用缓存数据还是网络数据:\n接口:" + api + "尚不存在缓存，采用网络数据");
            isNet = true;
        }
        return isNet;
    }


    /**
     * 通过时间来缓存数据
     *
     * @param time 时间
     * @param json 网络数据
     * @param api  api + 参数字典字符串
     */
    public static void saveJson(String json, long time, String api) {
        //缓存
        PreferenceUtil.putLong(api + "时间cache", time);
        PreferenceUtil.putString(api, json);
    }





    /**
     * 下载文件
     * */
  public static void downloadFile(final Handler mHandler,String url,String fileName,final int attachId){
	  
	  
	  url = StringEscapeUtils.unescapeHtml(url);
	  LogUtils.i("url::"+url);
      HttpUtils http = new HttpUtils();
     
      http.configRequestThreadPoolSize(3);
      if (fileName==null){
          fileName = url.substring(url.lastIndexOf('/') + 1);
          fileName = fileName.substring(fileName.lastIndexOf('&')+1);
//      try {
//          fileName = CommonUtil.getMD5(fileName);
//      } catch (NoSuchAlgorithmException e) {
//          e.printStackTrace();
//      }
      }
      //final Message msg = mHandler.obtainMessage();
      LogUtils.w("下载文件："+fileName);
      
      HttpHandler handler = http.download(url,
              "/sdcard/xiniu/"+fileName,
              true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
              true, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
              new RequestCallBack<File>() {

                  @Override
                  public void onStart() {
                      StringUtil.showToast("onStart");
                    
                  }

                  @Override
                  public void onLoading(long total, long current, boolean isUploading) {

                      LogUtils.e(""+total+","+current);
                      //System.out.println("--total-::"+total+"-current--::"+current);
                      
                      if(current==0){
                    	  Message msg = mHandler.obtainMessage();
                          msg.what = 4;
                          msg.arg2 = attachId;
                          mHandler.sendMessage(msg);
                      }else{
                    	  Message msg = mHandler.obtainMessage();
                    	  msg.what = 5;
                          msg.arg1 = (int)(current*100/total);
                          msg.arg2 = attachId;
                          mHandler.sendMessage(msg);
                      }
                      
                     
                  }

                  @Override
                  public void onSuccess(ResponseInfo<File> responseInfo) {
                      StringUtil.showToast("onSuccess");
                      LogUtils.e("onSuccess");
                      Message msg = mHandler.obtainMessage();
                      msg.what = 6;
                      msg.arg2 = attachId;
                      msg.obj = responseInfo.result;
                      mHandler.sendMessage(msg);
                  }


                  @Override
                  public void onFailure(HttpException error, String str) {
                      StringUtil.showToast(str);
                      LogUtils.e("onFailure:"+str);
                      Message msg = mHandler.obtainMessage();
                      msg.what = 7;
                      msg.obj = str;
                      mHandler.sendMessage(msg);
                  }
              });
  }

  	/**
  	 * 
  	 * @param mHandler
  	 * @param ctime 发送时间
  	 * @param to_id	收件人
  	 * @param subject	标题
  	 * @param content	内容
  	 * @param urls	附件路径集
  	 */
  	public static void email_add(final Handler mHandler,String ctime,String to_id,String subject,String content,String... urls){
  		RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("ctime", ctime);
            jsonObject.put("to_id", to_id);
            jsonObject.put("content", content);
            jsonObject.put("subject", subject);
            
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());
        if(urls!=null && urls.length!=0){
        	for(int i=0;i<urls.length;i++){
            	params.addBodyParameter("file"+i+1, new File(urls[i]));
            }
        }
        HttpUtils http = new HttpUtils();
        http.configSoTimeout(AppConfig.HTTP_TIMEOUT); // 设置请求超时

        final Message msg = mHandler.obtainMessage();
        http.send(HttpMethod.POST, AppConfig.CODE_EMAIL_ADD, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				System.out.println("------发送成功-----::"+responseInfo.result);
				if (responseInfo != null) {
                    //缓存
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responseInfo.result);
                        if ((jsonObject.getInt("state")) == 0) {
                            msg.what = -8;
                            msg.obj = jsonObject.getString("reason");
                        } else {
                            msg.what = 8;
                            msg.obj = jsonObject.getString("reason");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {
                        mHandler.sendMessage(msg);
                    }

                } else {
                    msg.what = -8;
                    msg.obj = "发送邮件失败！";
                    mHandler.sendMessage(msg);
                }
			}

			@Override
			public void onFailure(HttpException error, String reason) {
				System.out.println("------发送失败-----::"+msg);
				Message msg = mHandler.obtainMessage();
				msg.what = -8;
				msg.obj = reason;
				mHandler.sendMessage(msg);
			}
		});
  	}


    /**========== 请求  =============**/

    public static void login(final Handler mHandler, String username, String pwd) {

        RequestParams params = getRequestHead(true);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userid", username);
            jsonObject.put("passwd", pwd);
            jsonObject.put("token", "token");
            jsonObject.put("devicetype", "ANDROID");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());
        post(mHandler, AppConfig.CODE_LOG, params, 1, "登录",AppConfig.CACHE_TIME_SHORT);

    }

    public static void email(final Handler mHandler, String data1,
                             String data2, String subject, int page) {
        LogUtils.i("data1-->>" + data1 + "--data2-->>" + data2
                + "--subject-->>" + subject + "--page-->>" + page);
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("data1", data1);
            jsonObject.put("data2", data2);
            jsonObject.put("subject", subject);
            jsonObject.put("page", page);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_EMAIL, params, 2, "邮件列表",AppConfig.CACHE_TIME_SHORT);

    }

    public static void email_detail(final Handler mHandler, int email_id) {
        LogUtils.i("email_detail::email_id-->>" + email_id);
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("email_id", email_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_EMAIL_DETAIL, params, 3, "邮件详情",AppConfig.CACHE_TIME_SHORT);
    }

    public static void notify(final Handler mHandler, String subject, int page) {
        LogUtils.i("subject-->>" + "--page-->>" + page);
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("subject", subject);
            jsonObject.put("page", page);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_NOTIFY, params, 2, "公告列表",AppConfig.CACHE_TIME_SHORT);

    }

    public static void notify_detail(final Handler mHandler, String notify_id) {
        LogUtils.i("notify_detail--notify_id-->>" + notify_id);
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("notify_id", notify_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_NOTIFY_DETAIL, params, 4, "公告详情",AppConfig.CACHE_TIME_SHORT);

    }

    public static void news_detail(final Handler mHandler, String news_id) {
        LogUtils.i("news_detail--news_id-->>" + news_id);
//		HttpUtils http = new HttpUtils();
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("news_id", news_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_NEWS_DETAIL, params, 5, "新闻详情",AppConfig.CACHE_TIME_SHORT);

    }

    public static void news(final Handler mHandler, String date1, String date2,
                            String subject, int page) {
        LogUtils.i("-news-" + "data1-->>" + date1 + "--data2-->>" + date1
                + "--subject-->>" + subject + "--page-->>" + page);
        HttpUtils http = new HttpUtils();
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();
        try {

            jsonObject.put("date2", date2);
            jsonObject.put("subject", subject);
            jsonObject.put("page", page);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());
        post(mHandler, AppConfig.CODE_NEWS, params, 6, "新闻列表",AppConfig.CACHE_TIME_SHORT);
    }

    /**
     * 短信列表
     * */
    public static void sms(final Handler mHandler, String date1, String date2,
                           String content, int page) {
        LogUtils.i("sms--date1-->>" + date1 + "--date2-->>" + date2
                + "-->content-->>" + content + "--page-->>" + page);
        HttpUtils http = new HttpUtils();
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();

        try {

            jsonObject.put("date1", date1);
            jsonObject.put("date2", date2);
            jsonObject.put("content", content);
            jsonObject.put("page", page);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_SMS, params, 1, "短信",AppConfig.CACHE_TIME_SHORT);
    }

    /**
     * 发送短信
     * http://www.gzlxsoft.com:899/app/sms/add/?help=1
     * data={"ctime":"2015-05-06 23:35:10","to_id":"admin","content":"APP测试短信内容"}
     * */
    public static void smsAdd(final Handler mHandler, String ctime, String to_id,
                           String content,int floor) {
        LogUtils.i("sms--date1-->>" + ctime + "--date2-->>" + to_id
                + "-->content-->>" + content);
        HttpUtils http = new HttpUtils();
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();

        try {

            jsonObject.put("ctime", ctime);
            jsonObject.put("to_id", to_id);
            jsonObject.put("content", content);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_SMS_ADD, params, floor, "发送短信",AppConfig.CACHE_TIME_SHORT);
    }


    /**
     * 文件管理器
     * 请求基本参数样例：
     * data={"mf_id":"0","page":"1"}
     * 请求基本参数样例说明：
     * data={"mf_id":"根目录为0其他目录从查到的mf_id查其目录","page":"请求那一页数据"}
     * */
    public static void file(final Handler mHandler,int mf_id,int page) {

        LogUtils.i("file--mf_id-->>" + mf_id + "--page-->>" + page);
        HttpUtils http = new HttpUtils();
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();

        try {

            jsonObject.put("mf_id", mf_id);
            jsonObject.put("page", page);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_FILE, params, 1, "文件管理器",AppConfig.CACHE_TIME_SHORT);
    }

    public static void verupdate(Handler mHandler,String date){
        HttpUtils http = new HttpUtils();
        RequestParams params = getRequestHead(false);
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("date", date);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        params.addBodyParameter("data", jsonObject.toString());

        post(mHandler, AppConfig.CODE_VERUPDATE, params, 7, "版本",AppConfig.CACHE_TIME_SHORT);
    }

}
